<template>
  <div :class="className" :style="{height:height,width:width}" />
</template>

<script>
  import * as echarts from 'echarts'
  require('echarts/theme/macarons') // echarts theme
  import resize from './mixins/resize'
  import moment from 'moment';
  import { ProductQualifiedQuery, getYeild } from "@/api/system/datamanage"


  export default {
    mixins: [resize],
    props: {
      className: {
        type: String,
        default: 'chart'
      },
      width: {
        type: String,
        default: '100%'
      },
      height: {
        type: String,
        default: '350px'
      },
      autoResize: {
        type: Boolean,
        default: true
      },
      chartData: {
        type: Object,
        required: true
      }
    },
    data() {
      return {
        chart: null,
        times: [],
        values: [],
        legendList: [],
        seriesList: [],
        cumulativeData: []
      }
    },
    watch: {
      chartData: {
        deep: true,
        handler(val) {
          this.setOptions(val)
        }
      }
    },
    activated() {
      this.$nextTick(() => {
        this.initChart()
      })

      this.updateData();
      setInterval(this.updateData, 10 * 60 * 1000); // 每1小时更新一次
      // 设置定时任务，每天凌晨重置
      this.scheduleResetAtMidnight();
    },
    mounted() {
      this.$nextTick(() => {
        this.initChart()
      })

      this.updateData();
      setInterval(this.updateData, 10 * 60 * 1000); // 每1小时更新一次
      // 设置定时任务，每天凌晨重置
      this.scheduleResetAtMidnight();
    },
    deactivated() {
      if (!this.chart) {
        return
      }
      this.chart.dispose()
      this.chart = null
    },
    methods: {
      initChart() {
        this.chart = echarts.init(this.$el, 'macarons')
        this.setOptions(this.chartData)
      },
      setOptions({ expectedData, actualData } = {}) {
        this.chart.setOption({
          title: {
            text: '产量'
          },
          xAxis: {
            data: this.times,
            boundaryGap: false,
            axisTick: {
              show: false
            }
          },
          grid: {
            left: 40,
            right: 40,
            bottom: 20,
            top: 30,
            containLabel: true
          },
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'cross'
            },
            padding: [5, 10]
          },
          yAxis: {
            axisTick: {
              show: true
            }
          },
          legend: {
            data: this.legendList
          },
          series: this.seriesList
        })
      },
      async updateData() {
        // 获取当前时间
        const currentTime = moment().format('HH:mm');
        // 判断是否在更新范围内
        if (moment(currentTime, 'HH:mm').isBetween(moment('08:00', 'HH:mm'), moment('20:00', 'HH:mm'), null, '[]')) {

          // 如果当前时间不是整点，则不更新
          let newTime = ''
          newTime = (Number(currentTime.split(':')[0])+1)+':'+'00'
          console.log(9999,currentTime,newTime)
          if (newTime.split(':')[1] !== '00') return;
          // console.log(9999,currentTime.split(':')[1] !== '00')
          // 移除最早的一个时间数据
          this.times.shift();
          this.values.shift();

          // 添加当前的时间和数据
          this.times.push(newTime);
          // this.values.push(Math.floor(Math.random() * 100)); // 随机生成数据
          let startTime = this.parseTime(new Date(), '{y}-{m}-{d}') + ' ' + this.times[this.times.length - 2] + ':00';
          let endTime = this.parseTime(new Date(), '{y}-{m}-{d}') + ' ' + newTime + ':00';
          let params = {
            pageNum: 1,
            pageSize: 9999
          }
          await getYeild(this.addDateTimeRange(params, [startTime, endTime])).then(response => {

            if (response.data != null && response.data.length > 0) {
              this.qualifiedList = response.data;

              console.log(this.qualifiedList);
              this.qualifiedList.forEach(element => {
                let productName = element.productName
                if (!this.cumulativeData[productName]) {
                  this.cumulativeData[productName] = { acceptance: [], belowStandard: [] };
                }
                // 累积合格和不合格的数量
                this.cumulativeData[productName].acceptance.push(element.acceptanceNumber);
                this.cumulativeData[productName].belowStandard.push(element.belowStandardNumber);
              });
              for (var productName in this.cumulativeData) {
                this.legendList.push(productName + '-合格品');
                this.legendList.push(productName + '-不合格品');

                this.seriesList.push({
                  name: productName + '-合格品',
                  type: 'line',
                  data: this.cumulativeData[productName].acceptance,
                  lineStyle: {
                    color: productName === "5KA.206.140-name" ? 'green' : 'blue'
                  }
                });

                this.seriesList.push({
                  name: productName + '-不合格品',
                  type: 'line',
                  data: this.cumulativeData[productName].belowStandard,
                  lineStyle: {
                    color: productName === "5KA.206.140-name" ? 'red' : 'orange',
                    type: 'dashed'
                  }
                });
              }
            }


          });
          // 更新图表
          this.chart.setOption({
            xAxis: {
              data: this.times
            },
            legend: {
              data: this.legendList
            },
            series: this.seriesList
          });

          // 强制 Vue 重新渲染
          this.$forceUpdate();
        }
      },
      async initializeTimes() {
        // 获取当前时间
        const now = moment();

        // 初始化最近八个小时的时间
        for (let i = 0; i < 8; i++) {
          let time = ''
          // if(i==7){
          //    time = now.clone().add(1, 'hours').startOf('hour').format('HH:mm');
          // }else{
             time = now.clone().subtract(7 - i, 'hours').startOf('hour').format('HH:mm');
          // }

          this.times.push(time);
          // this.values.push(Math.floor(Math.random() * 100)); // 随机生成初始数据
        }
        for (let i = 1; i < 8; i++) {
          let startTime = this.parseTime(new Date(), '{y}-{m}-{d}') + ' ' + this.times[i - 1] + ':00';
          let endTime = this.parseTime(new Date(), '{y}-{m}-{d}') + ' ' + this.times[i] + ':00';

          let params = {
            pageNum: 1,
            pageSize: 9999
          }
          await getYeild(this.addDateTimeRange(params, [startTime, endTime])).then(response => {
            if (response.data != null && response.data.length > 0) {
              this.qualifiedList = response.data;
              this.qualifiedList.forEach(element => {
                let productName = element.productName
                if (!this.cumulativeData[productName]) {
                  this.cumulativeData[productName] = { acceptance: [], belowStandard: [] };
                }
                // 累积合格和不合格的数量
                this.cumulativeData[productName].acceptance.push(element.acceptanceNumber);
                this.cumulativeData[productName].belowStandard.push(element.belowStandardNumber);
              });

            }


          });
        }
        for (var productName in this.cumulativeData) {

          this.legendList.push(productName + '-合格品');
          this.legendList.push(productName + '-不合格品');
          this.seriesList.push({
            name: productName + '-合格品',
            type: 'line',
            data: this.cumulativeData[productName].acceptance,
            lineStyle: {
              color: productName === "5KA.206.140-name" ? 'green' : 'blue'
            }
          });

          this.seriesList.push({
            name: productName + '-不合格品',
            type: 'line',
            data: this.cumulativeData[productName].belowStandard,
            lineStyle: {
              color: productName === "5KA.206.140-name" ? 'red' : 'orange',
              type: 'dashed'
            }
          });
        }
        // 更新图表
        this.chart.setOption({
          xAxis: {
            data: this.times
          },
          legend: {
            data: this.legendList
          },
          series: this.seriesList
        });
      },
      scheduleResetAtMidnight() {
        // 计算距离下一个午夜的时间
        const now = moment();
        const nextMidnight = moment().startOf('day').add(1, 'day');
        const delay = nextMidnight.diff(now, 'milliseconds');

        // 在下一个午夜时重置图表
        setTimeout(() => {
          this.resetChart();
          // 每天凌晨重新设置定时任务
          setInterval(this.updateData, 10 * 60 * 1000); // 每1小时更新一次
          this.scheduleResetAtMidnight(); // 递归调用，确保每天凌晨都重置
        }, delay);
      },
      resetChart() {
        // 重置时间和数据
        this.times = [];
        this.values = [];
        this.initializeTimes();
        // 重新初始化图表
        this.initChart();
      }

    },
    created() {
      // 组件创建时初始化日期和数据
      this.initializeTimes();
      // 每天更新数据
    }
  }
</script>
